package com.gdcp.controller.backend;

import com.gdcp.beans.Order;
import com.gdcp.beans.OrderItem;
import com.gdcp.beans.User;
import com.gdcp.common.ResponseModel;
import com.gdcp.config.RequestHolder;
import com.gdcp.service.OrderItemService;
import com.gdcp.service.OrderService;
import com.gdcp.service.UserService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 杨华京
 * @version 1.0
 * @description
 * @since 1.8
 */
@Controller
@RequestMapping("/render/orderManager")
@RolesAllowed({"ROLE_ADMIN"})
public class OrderController_backend {

    @Autowired
    ResponseModel responseModel;
    @Autowired
    OrderService orderService;
    @Autowired
    OrderItemService orderItemService;
    @Autowired
    CommonCode commonCode;
    @Autowired
    UserService userService;

    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> list(int pageSize, int pageNumber, String sortName, String sortOrder){
        Map<String,Object> model=commonCode.getList(pageSize, pageNumber, sortName, sortOrder);
        return orderService.findPageBreakByCondition(model);
    }

    @RequestMapping(value = "/remove",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> remove(Integer[] ids){
        if (ids==null){
            return responseModel.setModel(false,"请至少选择一条记录");
        }

        return orderService.removeByPrimaryKey(ids);
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> add(String order_no, String user_id, String payment_type, String status){
        HttpServletRequest request= RequestHolder.getRequest();
        //需要有规定格式
        //String order_no= request.getParameter("order_no");
        if (user_id==null||user_id.equals("")){
            return responseModel.setModel(false,"下单失败！用户id不能为空");
        }
        if (payment_type==null||payment_type.equals("")){
            return responseModel.setModel(false,"下单失败！支付方式不能为空");
        }
        if (status==null||status.equals("")){
            return responseModel.setModel(false,"下单失败！状态不能为空");
        }
        Integer userId= Integer.valueOf(user_id);
        Integer paymentType= Integer.valueOf(request.getParameter("payment_type"));
        Integer statusIn= Integer.valueOf(request.getParameter("status"));

        User user=userService.getInformation(userId);
        if (user==null){
            return responseModel.setModel(false,"下单失败！该用户不存在"+user_id);
        }

        Order order=new Order();
        order.setOrder_no(order_no);
        order.setUser_id(userId);
        order.setPayment_type(paymentType);
        order.setStatus(statusIn);
        try{
            orderService.insert(order);
        }catch (Exception e){
            e.printStackTrace();
            return responseModel.setModel(false,"下单失败！");
        }
        return responseModel.setModel(true,"下单成功！");
    }

    @Transactional(rollbackFor = { Exception.class })
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> edit(Order order){
        if (order.getUser_id()!=null){
            User user=userService.getInformation(order.getUser_id());
            if (user==null){
                return responseModel.setModel(false,"下单失败！该用户不存在"+order.getUser_id());
            }
        }

        try{
            if (order.getStatus()==10) {
                order.setSend_time(new Date());
            }

            if (order.getStatus()==10){
                order.setStatus(20);
            }else {
                order.setStatus(order.getStatus());
            }

            orderService.updateInformation(order);

            List<OrderItem> orderItems=orderItemService.queryOrderItemByOid(order.getOrder_no());
            for (OrderItem orderItem:orderItems){
                if (order.getStatus()==10){
                    orderItem.setUser_status(20);
                    orderItem.setShop_status(30);
                }else {
                    orderItem.setUser_status(order.getStatus());
                    orderItem.setShop_status(order.getStatus());
                }

                int orderItem_count=orderItemService.updateInformation(orderItem);
                if (orderItem_count<0){
                    return responseModel.setModel(false,order.getStatus());
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return responseModel.setModel(false,"修改失败");
        }
        return responseModel.setModel(true,"修改成功");
    }

    @RequestMapping(value = "/get/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> get(@PathVariable Integer id){
        Order order=orderService.getInformation(id);
        if (order!=null){
            return responseModel.setModel(true,order);
        }

        return responseModel.setModel(false,"获取失败");
    }

    /*@RequestMapping(value = "/search/{id}",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> searchByOrderNo(String id){
        Map<String, Object> param=new HashMap<>();
        System.out.println(id);
        BigInteger order_no= BigInteger.valueOf(Long.valueOf(id));
        param.put("order_no", order_no);
        return orderService.searchInformation(param);
    }*/

    @RequestMapping(value = "/search",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> search(Integer pageSize, Integer pageNumber, String searchText, String sortName, String sortOrder){
        String str = "["+searchText+"]";
        JSONArray json= JSONArray.fromObject(str);
        Map<String, Object> param=new HashMap<>();

        //Integer a=null,b=null;
        //if (pageSize!=null){
        //    a =(pageNumber-1)*pageSize;
        //    b =pageSize;
        //}

        //param.put("a", a);
        //param.put("b", b);
        param.put("sortName", sortName);
        param.put("sortOrder", sortOrder);

        for(int i=0;i<json.size();i++){
            JSONObject jsonOne = json.getJSONObject(i);
            param.put("user_id", jsonOne.getString("user_id"));
            param.put("order_no", jsonOne.getString("order_no"));
            param.put("status", jsonOne.getString("status"));
        }

        return orderService.searchInformation(param);
    }
}
